package xy.come.juhenews.Uitils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.ColorInt;
import android.support.annotation.FloatRange;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.widget.ListView;
import android.widget.ScrollView;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Xia_焱 on 2018/10/25.
 * e-mail：XiahaotianV@163.com
 */

public class ConvertUtils {
    public static final long GB = 1073741824L;
    public static final long MB = 1048576L;
    public static final long KB = 1024L;

    public ConvertUtils() {
    }

    public static int toInt(Object obj) {
        try {
            return Integer.parseInt(obj.toString());
        } catch (NumberFormatException var2) {
            return -1;
        }
    }

    public static int toInt(byte[] bytes) {
        int result = 0;

        for (int i = 0; i < bytes.length; ++i) {
            byte abyte = bytes[i];
            result += (abyte & 255) << 8 * i;
        }

        return result;
    }

    public static int toShort(byte first, byte second) {
        return (first << 8) + (second & 255);
    }

    public static long toLong(Object obj) {
        try {
            return Long.parseLong(obj.toString());
        } catch (NumberFormatException var2) {
            return -1L;
        }
    }

    public static float toFloat(Object obj) {
        try {
            return Float.parseFloat(obj.toString());
        } catch (NumberFormatException var2) {
            return -1.0F;
        }
    }

    public static byte[] toByteArray(int i) {
        return ByteBuffer.allocate(4).putInt(i).array();
    }

    public static byte[] toByteArray(String hexData, boolean isHex) {
        if (hexData != null && !hexData.equals("")) {
            if (!isHex) {
                return hexData.getBytes();
            } else {
                hexData = hexData.replaceAll("\\s+", "");
                String hexDigits = "0123456789ABCDEF";
                ByteArrayOutputStream baos = new ByteArrayOutputStream(hexData.length() / 2);

                for (int i = 0; i < hexData.length(); i += 2) {
                    baos.write(hexDigits.indexOf(hexData.charAt(i)) << 4 | hexDigits.indexOf(hexData.charAt(i + 1)));
                }

                byte[] bytes = baos.toByteArray();

                try {
                    baos.close();
                } catch (IOException var6) {

                }

                return bytes;
            }
        } else {
            return null;
        }
    }

    public static String toHexString(String str) {
        if (TextUtils.isEmpty(str)) {
            return "";
        } else {
            StringBuilder builder = new StringBuilder();
            byte[] bytes = str.getBytes();
            byte[] var3 = bytes;
            int var4 = bytes.length;

            for (int var5 = 0; var5 < var4; ++var5) {
                byte aByte = var3[var5];
                builder.append(Integer.toHexString(255 & aByte));
                builder.append(" ");
            }

            return builder.toString();
        }
    }

    public static String toHexString(byte... bytes) {
        char[] DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] buffer = new char[bytes.length * 2];
        int i = 0;

        for (int var4 = 0; i < bytes.length; ++i) {
            int u = bytes[i] < 0 ? bytes[i] + 256 : bytes[i];
            buffer[var4++] = DIGITS[u >>> 4];
            buffer[var4++] = DIGITS[u & 15];
        }

        return new String(buffer);
    }

    public static String toHexString(int num) {
        String hexString = Integer.toHexString(num);

        return hexString;
    }

    public static String toBinaryString(byte... bytes) {
        char[] DIGITS = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        char[] buffer = new char[bytes.length * 8];
        int i = 0;

        for (int var4 = 0; i < bytes.length; ++i) {
            int u = bytes[i] < 0 ? bytes[i] + 256 : bytes[i];
            buffer[var4++] = DIGITS[u >>> 7 & 1];
            buffer[var4++] = DIGITS[u >>> 6 & 1];
            buffer[var4++] = DIGITS[u >>> 5 & 1];
            buffer[var4++] = DIGITS[u >>> 4 & 1];
            buffer[var4++] = DIGITS[u >>> 3 & 1];
            buffer[var4++] = DIGITS[u >>> 2 & 1];
            buffer[var4++] = DIGITS[u >>> 1 & 1];
            buffer[var4++] = DIGITS[u & 1];
        }

        return new String(buffer);
    }

    public static String toBinaryString(int num) {
        String binaryString = Integer.toBinaryString(num);

        return binaryString;
    }

    public static String toSlashString(String str) {
        String result = "";
        char[] chars = str.toCharArray();
        char[] var3 = chars;
        int var4 = chars.length;

        for (int var5 = 0; var5 < var4; ++var5) {
            char chr = var3[var5];
            if (chr == 34 || chr == 39 || chr == 92) {
                result = result + "\\";
            }

            result = result + chr;
        }

        return result;
    }

    public static <T> T[] toArray(List<T> list) {
        return (T[]) list.toArray();
    }

    public static <T> List<T> toList(T[] array) {
        return Arrays.asList(array);
    }

    public static String toString(Object[] objects) {
        return Arrays.deepToString(objects);
    }

    public static String toString(Object[] objects, String tag) {
        StringBuilder sb = new StringBuilder();
        Object[] var3 = objects;
        int var4 = objects.length;

        for (int var5 = 0; var5 < var4; ++var5) {
            Object object = var3[var5];
            sb.append(object);
            sb.append(tag);
        }

        return sb.toString();
    }

    public static byte[] toByteArray(InputStream is) {
        if (is == null) {
            return null;
        } else {
            try {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                byte[] buff = new byte[100];

                while (true) {
                    int len = is.read(buff, 0, 100);
                    if (len == -1) {
                        byte[] bytes = os.toByteArray();
                        os.close();
                        is.close();
                        return bytes;
                    }

                    os.write(buff, 0, len);
                }
            } catch (IOException var4) {

                return null;
            }
        }
    }

    public static byte[] toByteArray(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        } else {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
            byte[] bytes = os.toByteArray();

            try {
                os.close();
            } catch (IOException var4) {

            }

            return bytes;
        }
    }

    public static Bitmap toBitmap(byte[] bytes, int width, int height) {
        Bitmap bitmap = null;
        if (bytes.length != 0) {
            try {
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inDither = false;
                options.inPreferredConfig = null;
                if (width > 0 && height > 0) {
                    options.outWidth = width;
                    options.outHeight = height;
                }

                bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
                bitmap.setDensity(96);
            } catch (Exception var5) {

            }
        }

        return bitmap;
    }

    public static Bitmap toBitmap(byte[] bytes) {
        return toBitmap(bytes, -1, -1);
    }

    public static Bitmap toBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else {
            Bitmap bitmap;
            Canvas canvas;
            if (drawable instanceof ColorDrawable) {
                bitmap = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888);
                canvas = new Canvas(bitmap);
                canvas.drawColor(((ColorDrawable) drawable).getColor());
                return bitmap;
            } else if (drawable instanceof NinePatchDrawable) {
                bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
                canvas = new Canvas(bitmap);
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
                drawable.draw(canvas);
                return bitmap;
            } else {
                return null;
            }
        }
    }

    @TargetApi(19)
    public static String toPath(Context context, Uri uri) {
        if (uri == null) {

            return "";
        } else {

            String path = uri.getPath();
            String scheme = uri.getScheme();
            String authority = uri.getAuthority();
            boolean isKitKat = Build.VERSION.SDK_INT >= 19;
            if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                byte var11 = -1;
                switch (authority.hashCode()) {
                    case 320699453:
                        if (authority.equals("com.android.providers.downloads.documents")) {
                            var11 = 1;
                        }
                        break;
                    case 596745902:
                        if (authority.equals("com.android.externalstorage.documents")) {
                            var11 = 0;
                        }
                        break;
                    case 1734583286:
                        if (authority.equals("com.android.providers.media.documents")) {
                            var11 = 2;
                        }
                }

                switch (var11) {
                    case 0:
                        if ("primary".equalsIgnoreCase(type)) {
                            return Environment.getExternalStorageDirectory() + "/" + split[1];
                        }
                        break;
                    case 1:
                        contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId).longValue());
                        return _queryPathFromMediaStore(context, contentUri, (String) null, (String[]) null);
                    case 2:
                        if ("image".equals(type)) {
                            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                        } else if ("video".equals(type)) {
                            contentUri = android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                        } else if ("audio".equals(type)) {
                            contentUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                        }

                        String selection = "_id=?";
                        String[] selectionArgs = new String[]{split[1]};
                        return _queryPathFromMediaStore(context, contentUri, selection, selectionArgs);
                }
            } else {
                if ("content".equalsIgnoreCase(scheme)) {
                    if (authority.equals("com.google.android.apps.photos.content")) {
                        return uri.getLastPathSegment();
                    }

                    return _queryPathFromMediaStore(context, uri, (String) null, (String[]) null);
                }

                if ("file".equalsIgnoreCase(scheme)) {
                    return uri.getPath();
                }
            }


            return path;
        }
    }

    private static String _queryPathFromMediaStore(Context context, Uri uri, String selection, String[] selectionArgs) {
        String filePath = null;

        try {
            String[] projection = new String[]{"_data"};
            Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, (String) null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow("_data");
                cursor.moveToFirst();
                filePath = cursor.getString(column_index);
                cursor.close();
            }
        } catch (IllegalArgumentException var8) {

        }

        return filePath;
    }

    @SuppressLint("WrongConstant")
    public static Bitmap toBitmap(View view) {
        int width = view.getWidth();
        int height = view.getHeight();
        int color;
        if (view instanceof ListView) {
            height = 0;
            ListView listView = (ListView) view;

            for (color = 0; color < listView.getChildCount(); ++color) {
                height += listView.getChildAt(color).getHeight();
            }
        } else if (view instanceof ScrollView) {
            height = 0;
            ScrollView scrollView = (ScrollView) view;

            for (color = 0; color < scrollView.getChildCount(); ++color) {
                height += scrollView.getChildAt(color).getHeight();
            }
        }

        view.setDrawingCacheEnabled(true);
        view.clearFocus();
        view.setPressed(false);
        boolean willNotCache = view.willNotCacheDrawing();
        view.setWillNotCacheDrawing(false);
        color = view.getDrawingCacheBackgroundColor();
        view.setDrawingCacheBackgroundColor(-1);
        if (color != -1) {
            view.destroyDrawingCache();
        }

        view.buildDrawingCache();
        Bitmap cacheBitmap = view.getDrawingCache();
        if (cacheBitmap == null) {
            return null;
        } else {
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(cacheBitmap, 0.0F, 0.0F, (Paint) null);
            canvas.save();
            canvas.restore();
            if (!bitmap.isRecycled()) {

                bitmap.recycle();
            }

            view.destroyDrawingCache();
            view.setWillNotCacheDrawing(willNotCache);
            view.setDrawingCacheBackgroundColor(color);
            return bitmap;
        }
    }

    public static Drawable toDrawable(Bitmap bitmap) {
        return bitmap == null ? null : new BitmapDrawable(Resources.getSystem(), bitmap);
    }

    public static byte[] toByteArray(Drawable drawable) {
        return toByteArray(toBitmap(drawable));
    }

    public static Drawable toDrawable(byte[] bytes) {
        return toDrawable(toBitmap(bytes));
    }

    public static int toPx(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        int pxValue = (int) (dpValue * scale + 0.5F);
//        LogUtils.verbose(dpValue + " dp == " + pxValue + " px");
        return pxValue;
    }

    public static int toPx(float dpValue) {
        Resources resources = Resources.getSystem();
        float px = TypedValue.applyDimension(1, dpValue, resources.getDisplayMetrics());
        return (int) px;
    }

    public static int toDp(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        int dpValue = (int) (pxValue / scale + 0.5F);
       // LogUtils.verbose(pxValue + " px == " + dpValue + " dp");
        return dpValue;
    }

    public static int toSp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        int spValue = (int) (pxValue / fontScale + 0.5F);
       // LogUtils.verbose(pxValue + " px == " + spValue + " sp");
        return spValue;
    }

    public static String toGbk(String str) {
        try {
            return new String(str.getBytes("utf-8"), "gbk");
        } catch (UnsupportedEncodingException var2) {
           // LogUtils.warn(var2);
            return str;
        }
    }

    public static String toFileSizeString(long fileSize) {
        DecimalFormat df = new DecimalFormat("0.00");
        String fileSizeString;
        if (fileSize < 1024L) {
            fileSizeString = fileSize + "B";
        } else if (fileSize < 1048576L) {
            fileSizeString = df.format((double) fileSize / 1024.0D) + "K";
        } else if (fileSize < 1073741824L) {
            fileSizeString = df.format((double) fileSize / 1048576.0D) + "M";
        } else {
            fileSizeString = df.format((double) fileSize / 1.073741824E9D) + "G";
        }

        return fileSizeString;
    }

    public static String toString(InputStream is, String charset) {
        StringBuilder sb = new StringBuilder();

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));

            while (true) {
                String line = reader.readLine();
                if (line == null) {
                    reader.close();
                    is.close();
                    break;
                }

                sb.append(line).append("\n");
            }
        } catch (IOException var5) {
           // LogUtils.error(var5);
        }

        return sb.toString();
    }

    public static String toString(InputStream is) {
        return toString(is, "utf-8");
    }

    public static int toDarkenColor(@ColorInt int color) {
        return toDarkenColor(color, 0.8F);
    }

    public static int toDarkenColor(@ColorInt int color, @FloatRange(from = 0.0D, to = 1.0D) float value) {
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);
        hsv[2] *= value;
        return Color.HSVToColor(hsv);
    }

    public static String toColorString(@ColorInt int color) {
        return toColorString(color, false);
    }

    public static String toColorString(@ColorInt int color, boolean includeAlpha) {
        String alpha = Integer.toHexString(Color.alpha(color));
        String red = Integer.toHexString(Color.red(color));
        String green = Integer.toHexString(Color.green(color));
        String blue = Integer.toHexString(Color.blue(color));
        if (alpha.length() == 1) {
            alpha = "0" + alpha;
        }

        if (red.length() == 1) {
            red = "0" + red;
        }

        if (green.length() == 1) {
            green = "0" + green;
        }

        if (blue.length() == 1) {
            blue = "0" + blue;
        }

        String colorString;
        if (includeAlpha) {
            colorString = alpha + red + green + blue;
           // LogUtils.verbose(String.format(Locale.CHINA, "%d to color string is %s", new Object[]{Integer.valueOf(color), colorString}));
        } else {
            colorString = red + green + blue;
            //LogUtils.verbose(String.format(Locale.CHINA, "%d to color string is %s%s%s%s, exclude alpha is %s", new Object[]{Integer.valueOf(color), alpha, red, green, blue, colorString}));
        }

        return colorString;
    }

    public static ColorStateList toColorStateList(@ColorInt int normalColor, @ColorInt int pressedColor, @ColorInt int focusedColor, @ColorInt int unableColor) {
        int[] colors = new int[]{pressedColor, focusedColor, normalColor, focusedColor, unableColor, normalColor};
        int[][] states = new int[][]{{16842919, 16842910}, {16842910, 16842908}, {16842910}, {16842908}, {16842909}, new int[0]};
        return new ColorStateList(states, colors);
    }

    public static ColorStateList toColorStateList(@ColorInt int normalColor, @ColorInt int pressedColor) {
        return toColorStateList(normalColor, pressedColor, pressedColor, normalColor);
    }
}